<?php

namespace App\Admin\Actions;

use Dcat\Admin\Actions\Action;
use Dcat\Admin\Actions\Response;
use Dcat\Admin\Traits\HasPermissions;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Dcat\Admin\Grid\RowAction;


class RoomAction extends RowAction
{
    /**
     * @return string
     */
    protected $title = '用户';
    public $name = '批量复制';

    protected $model;

    public function __construct(string $model = null)
    {
        $this->model = $model;
    }

    /**
     * 返回字段标题
     *
     * @return string
     */
    public function title()
    {
        return '用户';
    }

    /**
     * Handle the action request.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function handle(Request $request)
    {
        // 获取当前行ID
        $id = $this->getKey();

        // 获取 parameters 方法传递的参数
        $username = $request->get('username');
        $model = $request->get('model');

        // 复制数据
        $model::find($id)->replicate()->save();

        // 返回响应结果并刷新页面
        return $this->response()->success("复制成功: [{$username}]")->refresh();
    }

    /**
     * 添加JS
     *
     * @return string
     */
    protected function script()
    {
        return <<<JS
        $('.grid-check-row').on('click', function () {

            // Your code.
            console.log($(this).data('id'));

        });
        JS;
    }


    /**
     * @return string|array|void
     */
    public function confirm()
    {
        return [
            // 确认弹窗 title
            "您确定要复制这行数据吗？",
            // 确认弹窗 content
            $this->row->login_name,
        ];
    }

    /**
     * @param Model|Authenticatable|HasPermissions|null $user
     *
     * @return bool
     */
    protected function authorize($user): bool
    {
        return true;
    }

    public function html()
    {
        // 获取当前行数据ID
        $id = $this->getKey();

        // 获取当前行数据的用户名
        $loginName = $this->row->login_name;

        // 这里需要添加一个class, 和上面script方法对应
        $this->setHtmlAttribute(['data-id' => $id, 'loginName' => $loginName, 'class' => 'grid-check-row']);

        return parent::html();
    }


    /**
     * @return array
     */
    protected function parameters()
    {
        return [
            // 发送当前行 username 字段数据到接口
            'loginName' => $this->row->login_name,
            // 把模型类名传递到接口
            'model' => $this->model,
        ];
    }
}
